/**
 * 
 */
package com.service.api.adcenter;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.pub.i.AttributesI;
import com.pub.util.HttpUtils;
import com.pub.util.XMLUtils;
import com.service.vo.KeywordVo;

/**
 * @author iling
 *
 */
public class GetDomainMatchRelatedKeywords implements AttributesI
{
	private int offset	= 0;
	private int limit	= 10;

	private String RequestURL;
	
	public GetDomainMatchRelatedKeywords(ResourceBundle rb)
	{
		RequestURL 	= rb.getString("domain.match.url");
	}
	
	public void setOffset(int offset) 
	{
		this.offset = offset;
	}
	
	public void setLimit(int limit)
	{
		this.limit	= limit;
	}

	public List<KeywordVo> getKeywords(String keywords) throws IOException, SAXException, ParserConfigurationException
	{
		StringBuilder url = new StringBuilder(200);
		
		url.append(RequestURL);
		
		url.append("&maxRT=");
		url.append(limit + offset);
		
		url.append("&seedTerm=");
		url.append(URLEncoder.encode(keywords, "UTF-8"));
		
		KeywordVo keywordVO;
		
		List<KeywordVo> keywordList = null;
		
		HttpURLConnection connSetURL;
		
		
		connSetURL = HttpUtils.getHttpConnURL(url.toString(), HttpUtils.METHOD.GET);
		
		ArrayList<Map<String, String>> alData;
		
		Document doc = XMLUtils.getDocument(connSetURL);
		
		alData = XMLUtils.getData(doc, "Search");
		
		keywordList = new ArrayList<KeywordVo>(alData.size() + 1);
		

		for(Map<String, String> data: alData){
			if(data.get("Search") == null || data.get("Search").length() == 0 || data.get("Search").equalsIgnoreCase(keywords))
				continue;
			
			keywordVO = new KeywordVo();
    		
    		keywordVO.setKeyword(data.get("Search"));
    		
    		keywordList.add(keywordVO);
		}
		
		return keywordList;
	}
}
